package dao;

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;


public class BaseDao {
    //数据库驱动字符串
    static String driver;
    //连接 URL 字符串
    static String url;
    //数据库用户名
    static String username;
    //用户密码
    static String password;

    protected Connection conn=null;
    protected PreparedStatement pstmt=null;
    protected ResultSet rs=null;
    static {
        init();
        try {
            Class.forName(driver);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
    //    加载驱动
    public static void init(){
        String configFile="database.properties";
        Properties pro=new Properties();
        InputStream is= BaseDao.class.getClassLoader().getResourceAsStream(configFile);
        try {
            pro.load(is);
            driver=pro.getProperty("driver");
            url=pro.getProperty("url");
            username=pro.getProperty("username");
            password=pro.getProperty("password");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    //    获取连接对象
    public Connection getConnection(){
        try {
            if (conn==null || conn.isClosed()){
                conn= DriverManager.getConnection(url,username,password);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }
    //    释放资源
    public void closeAll(Connection conn, Statement stm, ResultSet rs){
        try {
            if (conn!=null){
                conn.close();
            }
            if (stm!=null){
                stm.close();
            }
            if (rs!=null){
                rs.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
